package com.gjintel.framework.common.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gjintel.auction.business.model.AuctionInfo;
import com.gjintel.auction.business.service.IAuctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gjintel.business.proj.model.ComposeIdPK;
import com.gjintel.business.proj.model.DepositReturn;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.service.IDepositReturnService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.framework.common.service.IDepositExecuteService;
import com.gjintel.framework.common.service.IDepositService;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.SocketUtil;
import com.gjintel.framework.util.XmlParserUtil;
import com.gjintel.framework.util.dto.Bank;
import com.gjintel.framework.util.dto.Head;
import com.gjintel.framework.util.dto.JXml;

@Service("executeDepositService")
public class DepositExecuteServiceImpl implements IDepositExecuteService{

	@Value("${bank.serverIp}")
	private String bankServerIp;
	
	@Value("${bank.serverPort}")
	private String bankServerPort;
	
	//采购中心的银行帐号
	@Value("${center.account}")
	private String centerAccount;  
	
	final String modelPath = URLDecoder.decode( IDepositService.class.getResource("/bank").getPath(),"utf-8");
	
	@Autowired
	private IProjectInfoService projectInfoService;
	
	@Autowired
	private IDepositReturnService depositReturnService;

	@Autowired
	private IAuctionService auctionService;

	public DepositExecuteServiceImpl() throws UnsupportedEncodingException {
	}

	@Override
	public int regToBank(String projId) throws IOException, SocketException {
		 String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+"3001_2.xml");
		 Map m = new HashMap();
         AuctionInfo dto= auctionService.get(AuctionInfo.class, projId);
         m.put("dto", dto);
         m.put("centerAccount", centerAccount);
         m.put("transDate", new Date());
         m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
          
         String _xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);        //在字串中替换变量
         String _pre=String.format("%06d",_xmlStr.getBytes("gbk").length);				//计算字节长度，并以6位前缀补0
         String _ret = SocketUtil.socketPost(_pre+_xmlStr, bankServerIp, //发送socket 请求
          		Integer.parseInt(bankServerPort));
         if(!_ret.equals("")){											//对 _ret进行xml解析
          	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
          	Head h=jxml.getHead();
          	if(h.getTransCode().equals("3002")){  						//验证返回的是3002
          		String _iAcctNo=jxml.getBody().getiAcctNo();
          		String _authCode=jxml.getBody().getAuthCode();
          		if(_iAcctNo!=null && !_iAcctNo.equals("")){
          			dto.setExecuteBankAccount(_iAcctNo);				//对project的返回值 进行处理，保存虚拟帐号。
          		    dto.setExecuteBankAuthCode(_authCode);
          		    auctionService.saveOrUpdate(dto);
          		}else{
          		//TODO ：保存数据出错的异常捕获
          			return 0;
          		}
          		return 1;
          	}else{
          		//throws Exception
          		return 0;
          	}
          	
          }else{
          	return 0;
          }
	}

	@Override
	public int sendReturnDeposit(String bidderId, String projId, String bidderName, String projName,ComposeIdPK pk) {
		try {
			//项目信息
			AuctionInfo pro = auctionService.get(AuctionInfo.class, projId);
			
			String _xmlStr0 = CommUtil.readStringFromFile(modelPath + "/" + "3031_2.xml");
			Map m = new HashMap();
			AuctionInfo dto = auctionService.get(AuctionInfo.class, projId);
			m.put("dto", dto);
			//投标人信息
            RegisterUser user = this.auctionService.get(RegisterUser.class, bidderId);
            m.put("user", user);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            //交易流水号
            //DepositReturn deposit = depositReturnService.getDepositReturnByProjIdAndCompanyName(projId, user.getLoginName());
            DepositReturn deposit =auctionService.get(DepositReturn.class, pk);
            
            //System.out.println("++++++++++++++++++++++++++++++++ deposit: "+deposit.getHstSeqNum());
            m.put("deposit", deposit);
            
            //总笔数(默认为1条)
            int totalNum=1;
            m.put("totalNum", totalNum);
            
			String xmlStr = CommUtil.freemarkerProcess(m, _xmlStr0); // 在字串中替换变量
			String _pre = String.format("%06d", xmlStr.getBytes("gbk").length); // 计算字节长度，并以6位前缀补0
			System.out.println("++++++++++++++++++++++++++++++++ _pre+xmlStr: "+_pre+xmlStr);
			String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     // 发送socket// 请求
            		Integer.parseInt(bankServerPort));
			if (!_ret.equals("")) {
				// 对 _ret进行xml解析
				JXml jxml = XmlParserUtil.xmlParserJavaBean(_ret);
				Head h = jxml.getHead();
				if (h.getTransCode().equals("3032")) {
					// 对返回值做判断
					// 是否已提交成功
					String isResult = jxml.getBody().getBank().get(0).getResult();// 0 ：否  ，1 ：是
					return isResult==null?-1:Integer.valueOf(isResult);
				}
            }
		} catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return 0;
		}
		return 0;
	}

	@Override
	public List<Bank> searchReturnDepositByProj(String projId, String projName) {
		//退款明细查询
		try {
            String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+"3051_2.xml");
            
			Map m = new HashMap();
			//项目信息
            AuctionInfo dto= auctionService.get(AuctionInfo.class, projId);
            m.put("dto", dto);
            //基本信息
            m.put("date", new Date());
            
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            String xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);             //在字串中替换变量
            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
            		Integer.parseInt(bankServerPort));
            
            if(!_ret.equals("")){
            	//对 _ret进行xml解析
            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
            	Head h=jxml.getHead();
            	if(h.getTransCode().equals("3052")){  
            		//对返回值做处理
            		return jxml.getBody().getBank();
            	}
            }
        } catch (Exception e) {
			System.err.println("Error" + e); // 出错，则打印出错信息
			return null;
		}
		return null;
	}

	@Override
	public List<Bank> getDepositList(String projId) {
		try {
            String _xmlStr0=CommUtil.readStringFromFile(modelPath+"/"+"4011_2.xml");
           
			Map m = new HashMap();
			//项目信息
            AuctionInfo dto= auctionService.get(AuctionInfo.class, projId);
            m.put("dto", dto);
            //基本信息
            m.put("date", new Date());
            m.put("seqNo", System.currentTimeMillis()+"");											//生成序列号
            
            String xmlStr = CommUtil.freemarkerProcess(m,_xmlStr0);             //在字串中替换变量
            String _pre=String.format("%06d",xmlStr.getBytes("gbk").length);                //计算字节长度，并以6位前缀补0
            String _ret = SocketUtil.socketPost(_pre+xmlStr, bankServerIp,     //发送socket 请求
            		Integer.parseInt(bankServerPort));
            
            if(!_ret.equals("")){
            	//对 _ret进行xml解析
            	JXml jxml= XmlParserUtil.xmlParserJavaBean(_ret);
            	Head h=jxml.getHead();
            	if(h.getTransCode().equals("3012")){  
            		//对返回值做
            		return jxml.getBody().getBank();
            	}
            }
        } catch (Exception e) {
			System.out.println("Error" + e); // 出错，则打印出错信息
			return null;
		}
    			
		return null;
	}

}
